<template>
<div id="info" class="bg-assist">
	<div v-show="editProperty == ''">
		<sub-page-header title="个人资料" style="background-color: #b21014;color: #fff;"></sub-page-header>
		<ul class="info">
			<li>
				<div class="pull-left">头像</div>
				<div class="pull-right" @click="showFileSelect">
					<img class="avatar" :src="user.avatar" alt="">
					<i class="iconfont icon-right pull-right avatar-right"></i>
					<input @change="showCropper" type="file" ref="avatarUpload" class="avatar-upload" style="display:none;">
				</div>
			</li>
			<li @click="editProperty = 'nickname'">
				<div class="pull-left">昵称</div>
				<div class="pull-right">{{user.nickname}} <i class="iconfont icon-right"></i></div>
			</li>
			<li @click="editProperty = 'phone'">
				<div class="pull-left">手机号码</div>
				<div class="pull-right">{{user.phone}} <i class="iconfont icon-right"></i></div>
			</li>
		</ul>
		<ul class="info">
			<li @click="editProperty = 'username'">
				<div class="pull-left">真实姓名</div>
				<div class="pull-right">{{user.username}} <i class="iconfont icon-right"></i></div>
			</li>
			<li  @click="editProperty = 'email'">
				<div class="pull-left">电子邮箱</div>
				<div class="pull-right">{{user.email}} <i class="iconfont icon-right"></i></div>
			</li>
			<li @click="sexPicker.show()">
				<div class="pull-left">性别</div>
				<div class="pull-right">{{user.sex == 0 ? '男' : '女'}} <i class="iconfont icon-right"></i></div>
			</li>
			<li @click="birthdayPicker.show();">
				<div class="pull-left">出生日期</div>
				<div class="pull-right">{{user.birthday}} <i class="iconfont icon-right"></i></div>
			</li>

			<li @click="editProperty = 'pay_pass'">
				<div class="pull-left">支付密码</div>
				<div class="pull-right">修改 <i class="iconfont icon-right"></i></div>
			</li>
		</ul>
	</div>

	<div v-show="editProperty == 'pay_pass'" class="modal">
		<sub-page-header :triggerBack="true" @back="editProperty = ''" title="修改支付密码" style="background-color: #b21014;color: #fff;"></sub-page-header>
		<div class="edit-line">
			<input type="password" v-model="user.old_pay_pass" placeholder="旧支付密码" />
		</div>
		<div class="edit-line">
			<input type="password" v-model="user.pay_pass" placeholder="支付密码" />
		</div>
		<button @click="save('pay_pass')" class="btn btn-normal btn-rect btn-block">保存</button>
		<span @click="editProperty = 'reset_pay_pass'" class="forgot">忘记支付密码？</span>
	</div>

	<div v-show="editProperty == 'reset_pay_pass'" class="modal">
		<sub-page-header :triggerBack="true" @back="editProperty = ''" title="重置支付密码" style="background-color: #b21014;color: #fff;"></sub-page-header>
		<div class="edit-line">
			<input v-model="forgot.validateCode" placeholder="验证码"  style="width: 60%;float:left;box-sizing:border-box;"/>
			<el-button type="button"
				style="width: 40%;float: left;height: 54px;"
				class="btn btn-rect auth-btn"
				@click="sendEmail"
				:disabled="emailtimeout > 0">{{emailtimeout == 0 ? '发送邮件' : emailtimeout+'后重发'}}</el-button>
		</div>
		<div class="edit-line">
			<input type="password" v-model="forgot.pay_pass" placeholder="新支付密码">
		</div>
		<button @click="reset_pay_pass()" class="btn btn-normal btn-rect btn-block">保存</button>
	</div>

	<div v-show="editProperty == 'nickname'" class="modal">
		<sub-page-header :triggerBack="true" @back="editProperty = ''" title="修改昵称" style="background-color: #b21014;color: #fff;"></sub-page-header>
		<div class="edit-line">
			<input type="text" v-model="user.nickname" placeholder="输入昵称">
		</div>
		<button @click="save('nickname')" class="btn btn-normal btn-rect btn-block">保存</button>
	</div>

	<div v-show="editProperty == 'phone'" class="modal">
		<sub-page-header :triggerBack="true" @back="editProperty = ''" title="修改手机号码" style="background-color: #b21014;color: #fff;"></sub-page-header>
		<div class="edit-line">
			<input type="text" v-model="user.phone" placeholder="填写新手机号码">
		</div>
		<div class="edit-line">
			<input type="text" style="width: 50%" v-model="verifyCode" placeholder="手机验证码">
			<el-button class="send-sms-btn" @click="sendVerifyCode" :disabled="timeout > 0">{{verifyCodeButtonText}}</el-button>
		</div>
		<button @click="save('phone')" class="btn btn-normal btn-rect btn-block">保存</button>
	</div>

	<div v-show="editProperty == 'username'" class="modal user-modal">
		<sub-page-header :triggerBack="true" @back="editProperty = ''" title="修改真实姓名" style="background-color: #b21014;color: #fff;"></sub-page-header>
		<div class="edit-line">
			<el-row>
				<el-col :span="12">
					<input type="text" v-model="user.firstname" placeholder="姓氏">
				</el-col>
				<el-col :span="12">
					<input type="text" v-model="user.lastname" placeholder="名称">
				</el-col>
			</el-row>
		</div>
		<button @click="save('username')" class="btn btn-normal btn-rect btn-block">保存</button>
	</div>

	<div v-show="editProperty == 'email'" class="modal">
		<sub-page-header :triggerBack="true" @back="editProperty = ''" title="修改邮箱" style="background-color: #b21014;color: #fff;"></sub-page-header>
		<div class="edit-line">
			<input type="text" v-model="user.email" placeholder="输入邮箱">
		</div>
		<button @click="save('email')" class="btn btn-normal btn-rect btn-block">保存</button>
	</div>

	<div v-show="editProperty == 'avatar'" class="modal avatar-modal">
		<img class="edit-avatar" src="" ref="showImg" alt="">
		<i @click="cancelAvatar" class="iconfont icon-chacha pull-left"></i>
		<i @click="saveAvatar" class="iconfont icon-paying pull-right"></i>
	</div>
</div>
</template>

<script>
import SubPageHeader from '~/components/SubPageHeader.vue';
import AuthInput from '~/components/AuthInput.vue';
import api from '~/api/api.js';
import axios from 'axios';
import Cropper from 'cropperjs';
import css from '@/cropperjs/dist/cropper.min.css';
import Picker from 'better-picker';
import { compressImage } from '~/utils/index.js';

export default {
	components: {
		SubPageHeader,
		AuthInput
	},
	data () {
		return {
			// 正在编辑的属性
			editProperty: '',
			// 验证码
			verifyCode: '',
			timeout: 0,
			emailtimeout: 0,
			// 裁剪工具对象
			cropper: null,
			// 出生日期选择器
			birthdayPicker: null,
			// 性别选择器
			sexPicker: null,
			sexes: [
				{
					value: '0',
					label: '男'
				},
				{
					value: '1',
					label: '女'
				}
			],
			user: {},
			forgot: {
				validateCode: '',
				pay_pass: ''
			}
		}
	},
	computed: {
		verifyCodeButtonText () {
			return this.timeout == 0 ? '发送验证码' : this.timeout+'秒';
		}
	},
	created () {
		api.get('/user/info')
		.then(response => {
			this.user = response.data;
			// 性别选择
			this.sexPicker = new Picker({
				data: [
					[
						{
							text: '男',
							value: 0
						},
						{
							text: '女',
							value: 1
						}
					]
				],
				selectedIndex: [this.user.sex],
				title: '选择性别'
			});
			this.sexPicker.on('picker.valuechange', (selectedVal, selectedIndex) => {
				this.user.sex = selectedVal[0];
				this.save('sex');
			});
		});

		// 出生日期选择初始化
		let years = [];
		let months = [];
		let days = [];
		for(let k=1900;k < (new Date()).getFullYear(); k++) {
			years.push({
				text: k,
				value: k
			});
		}
		for(let k = 1; k < 13; k++) {
			let val = k > 9 ? k : '0'+k;
			months.push({
				text: val,
				value: val
			});
		}
		for(let k = 1; k < 32; k++) {
			let val = k > 9 ? k : '0'+k;
			days.push({
				text: val,
				value: val
			});
		}
		this.birthdayPicker = new Picker({
			data: [years, months, days],
			selectedIndex: [years.length - 20, 0, 0],
			title: '出生日期'
		});
		this.birthdayPicker.on('picker.valuechange', (selectedVal, selectedIndex) => {
			this.user.birthday = selectedVal.join('-');
			this.save('birthday');
		});
	},
	methods: {
		// 显示选择文件
		showFileSelect () {
			this.$refs.avatarUpload.click();
		},
		// 读取图像显示裁剪工具
		showCropper (event) {
			let file = event.target.files[0];
			if (!file) {
				return;
			}

			var img = this.$refs.showImg;
			let reader = new FileReader();
			let compress = false;
			reader.onload = (e) => {
				img.src = e.target.result;
			}
			reader.readAsDataURL(file);
			this.editProperty = 'avatar';

			img.onload = () => {
				if (file.size > 1024*1024 && !compress) {
					// 图片大于1m 则前台压缩一些
					compress = true;
					img.src = compressImage(img, 300, img.height*300/img.width, 0.5);
					return;
				}
				this.cropper = new Cropper(this.$refs.showImg, {
					aspectRatio: 1,
					dragMode: 'move',
					autoCropArea: 0.5,
					guides: false,
				    viewMode: 1,
				    background:false,
				    zoomable: false,
				    minContainerHeight: window.outerHeight,
				    // cropBoxResizable: false,
				    ready: function () {
				        self.croppable = true;
				    }
				});
			}
		},
		saveAvatar () {
			let base64Url = this.cropper.getCroppedCanvas().toDataURL();
			let formdata = new FormData();
			formdata.append('base64_string', base64Url);
			axios.post('/api/user/avatar', formdata)
			.then(response => {
				this.user.avatar = response.data.avatar;
				this.save('avatar');
			})
			.catch(error => {
				if (error.response.status == 422) {
					this.$message.error(error.message);
				}
			});
		},
		cancelAvatar () {
			this.editProperty = '';
			this.$refs.avatarUpload.value = '';
			this.cropper.destroy();
		},
		// 保存修稿
		save (profile) {
			if (profile == 'username') {
				this.user.username = this.user.firstname + this.user.lastname;
			}
			let data = {
				[profile] : this.user[profile]
			};

			if (profile) {
				data.old_pay_pass = this.user.old_pay_pass;
			}

			api.post('/user/save?code='+this.verifyCode, data)
			.then(response => {
				this.$message.success('保存成功');
			})
			.catch(error => {
				this.$message.error('保存失败');
			});
			this.editProperty = '';
		},
		// 发送验证码
		sendVerifyCode () {
			if (this.timeout > 0) {
				return ;
			}
			if (!/^1[0-9]{10}/.test(this.user.phone)) {
				return this.$message.warning('请输入正确的手机号码');
			}
			api.post('/sms/send', {
				type: 'bindPhone',
				phone: this.user.phone
			})
			.then(response => {
				this.$message.success('发送成功');
			});
			this.timeout = 60;
			let timefunc = () => {
				this.timeout--;
				if (this.timeout > 0) {
					setTimeout(timefunc, 1000);
				}
			}
			setTimeout(timefunc, 1000);
		},
		setSex (gIndex, iIndex) {
			this.user.sex = iIndex;
			this.save('sex');
		},
		sendEmail () {
			if (/^[\.a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]{2,4}$/.test(this.user.email)) {
				api.post('/forgot/send_email', {
					email: this.user.email
				})
				.then(response => {
					this.$message('发送成功');
				})
				.catch(error => {
					this.$message.error('验证码发送失败');
				})
				this.emailtimeout = 60;
				let stepFn = () => {
					this.emailtimeout--;
					if (this.emailtimeout > 0) {
						setTimeout(stepFn, 1000);
					}
				}
				setTimeout(stepFn, 1000);
			} else {
				this.$message('请先填写正确的邮箱');
			}
		},
		reset_pay_pass () {
			if (!this.forgot.validateCode || !this.forgot.pay_pass) {
				return this.$message.error('请填写支付密码和验证码');
			}

			api.post('/user/reset_pay_pass', {
				validate: this.forgot.validateCode,
				pay_pass: this.forgot.pay_pass
			})
			.then((data) => {
				this.$message.success('重置成功');
				this.editProperty = '';
			})
			.catch((err) => {
				this.$message.error(err.message);
			})
		}
	}
}
</script>

<style scoped>
.info {
	background-color: #fff;
	margin-bottom: 15px;
}

.info .avatar {
	width: 40px;
	height: 40px;
	border-radius: 50%;
}

.info .avatar-right {
	line-height: 40px;
	margin-left: 10px;
}

.info li {
	padding: 15px;
	overflow: hidden;
	border-bottom: 1px solid #eaeaea;
}

.edit-line {
	border-top: 1px solid #eaeaea;
}

.edit-line input {
	height: 54px;
	padding: 0px 10px;
	width: 100%;
	font-size: 14px;
	border: none;
}

.modal .btn-block {
	margin-top: 20px;
	height: 54px;
	width: 90%;
	display: block;
	margin-left: auto;
	margin-right: auto;
}

.edit-avatar {
	max-width: 100%;
	max-height: 100%;
}
.avatar-modal .iconfont{
	font-size: 40px;
	position: fixed;
	bottom: 100px;
}
.avatar-modal .icon-chacha {
	color: #fff;
	left: 30px;
}

.avatar-modal .icon-paying {
	color: #2ef32e;
	right: 30px;
	font-weight: 550;
}
.user-modal input{
	padding: 0;
	width: 90%;
	margin-left: 5%;
}
.send-sms-btn {
    margin: 10px 2.5%;
    color: rgb(255, 102, 0);
    max-width: 35%;
}
.forgot {
	float: right;
	margin: 10px;
	color: #b21014;
}
</style>
